package com.moss.cloud.common.security.config;

import com.alibaba.fastjson2.JSONObject;
import com.moss.cloud.common.core.custom.CustomHttpHeaders;
import com.moss.cloud.common.core.enums.GrantTypeEnum;
import com.moss.cloud.common.core.model.from.AuthFrom;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.security.condition.CustomCondition;
import com.moss.cloud.common.security.permission.AuthRpcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

/**
 * 初始化客户端认证
 *
 * @author 瑾年
 * @date 2023年11月17日
 */
@Slf4j
@Order(0)
@Conditional(CustomCondition.class)
@Configuration
public class InitializedEventConfig {
    @Value("${moss.cloud.clientId}")
    private String clientId;
    @Value("${moss.cloud.clientSecret}")
    private String clientSecret;
    private final AuthRpcService authRpcService;

    public InitializedEventConfig(AuthRpcService authRpcService) {
        this.authRpcService = authRpcService;
    }

    @Order
    @EventListener({WebServerInitializedEvent.class})
    @Async("asyncServiceExecutor")
    public void initializeClientSide() {
        log.info("初始化客户端认证:{}", clientId);
        String authorization = GrantTypeEnum.DEF_AUTHORIZATION.getValue();
        AuthFrom authFrom = GrantTypeEnum.authFrom(clientId, clientSecret);
        JSONObject json = authRpcService.token(authorization, CustomHttpHeaders.FORM_URLENCODED, CustomHttpHeaders.CACHE_CONTROL, authFrom);
        String headerValue = json.getString(GrantTypeEnum.ACCESS_TOKEN.getValue());
        BooleanHandel.isTrue(StringUtils.isNotBlank(headerValue)).trueHandle(() -> log.info("初始化客户端认证成功，客户端ID:{}", clientId));
    }
}
